package tmi.li.txwthr;



import java.util.Locale;

import android.app.PendingIntent;
import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.graphics.Color;
import android.os.Build.VERSION;
import android.os.Bundle;
import android.os.IBinder;
import android.widget.RemoteViews;


import tmi.li.txwthr.R;


public class TxWthrProvider extends AppWidgetProvider {
	//private static String TAG = "tmi.li.txwthr.TxWthrProvider";
	
	@Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
		TxPref txpref = new TxPref(TxPref.PREFS_NAME_TXWTHR);
		for(int i = 0; i < appWidgetIds.length; i++) {
			if(txpref.getPrefs(context, appWidgetIds[i])!= null) {
				Intent test = new Intent(context, Update.class);
				test.putExtra("Id", appWidgetIds[i]);
				context.startService(test);
				updateWidget(context, appWidgetManager, appWidgetIds[i]);
			}     	
		}		
    }
		
    static public void updateWidget(Context context, AppWidgetManager appWidgetManager, int appWidgetId) {
    	
    	//getting the Preferences of the widget
    	TxPref txpref = new TxPref(TxPref.PREFS_NAME_TXWTHR);
    	String s = txpref.getPrefs(context, Integer.valueOf(appWidgetId));
    	
    	// if s == null the Configuration Dialog hasnt ended yet, so do nothin
    	if(s != null ) {	
    		
    		String[] prefs = s.split(";");
    		String bhex = prefs[0];
    		String hex = prefs[1];
    		
    		//if prefs.length < 4 then the build update for the first time isnt finished
	        if(prefs.length > 4) {
	        	String _desc = "";
	        	String _desc2 = "";
		        String _current = prefs[4];  	
		    	if(prefs.length > 5)
		    		_desc = prefs[5];
		    	if(prefs.length > 6) {
		    		_desc2 = prefs[6];
		    	}else {
		    		_desc2 = "";
		    	}
		        
		    	//getting the Widget views
		        RemoteViews views = null;   
		        views = new RemoteViews(context.getPackageName(), R.layout.widget_layout);
		        
		        //if the sdk version is >= 8 aka android 2.2 froyo set the Background color
		        if(VERSION.SDK_INT >= 8) {
		        	views.setInt(R.id.lWidget, "setBackgroundColor", Color.parseColor(bhex));
		        }
		        
		        //setting the current temperature and description
		        views.setTextViewText(R.id.TextView01, _current);
		        views.setTextViewText(R.id.TextView02, _desc);
		        views.setTextViewText(R.id.TextView03, _desc2);
		        
		        //setting the Font Color for the Widget
		        views.setTextColor(R.id.TextView01, Color.parseColor(hex));
		        views.setTextColor(R.id.TextView02, Color.parseColor(hex));
		        views.setTextColor(R.id.TextView03, Color.parseColor(hex));
		        
		        //setting the OnClick Pending INtent for the whole Layout
		      //setting the OnClick Pending INtent for the whole Layout
		        if(txpref.getAppName(context, appWidgetId) != null) {
		           	String appname = txpref.getAppName(context, appWidgetId);
		           	Intent intent = new Intent(Intent.ACTION_MAIN);
		        	intent.setComponent(ComponentName.unflattenFromString(appname));
		        	PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
		        	views.setOnClickPendingIntent(R.id.lWidget, pendingIntent);
		        }

		        //stopping the service since i got the update alrdy
		        Intent service = new Intent(context, Update.class);
		        context.stopService(service);
				
				//updating the widget via the widget manager
		        appWidgetManager.updateAppWidget(appWidgetId, views);
		        
	        }else {
	        	//no updates yet so try to get new ones asap
	        	Intent test = new Intent(context, Update.class);
				test.putExtra("Id", appWidgetId);
				context.startService(test);
	        }
    	}
    }
    
    @Override
    public void onDeleted(Context context, int[] appWidgetIds) {
    	
        // When the user deletes the widget, delete the preference associated with it.
    	TxPref txpref = new TxPref(TxPref.PREFS_NAME_TXWTHR);
        final int N = appWidgetIds.length;
        for (int i=0; i<N; i++) {
            txpref.deletePreAndId(context, appWidgetIds[i]);
        }
    }
	
	public static class Update extends Service {
		private WeatherUpdate updt = new WeatherUpdate();
		
	    @Override
	    public void onStart(Intent intent, int startId) {
	    	
	    	//registering TxWthrReceiver for various Broadcasts 
			IntentFilter it = new IntentFilter(Intent.ACTION_SCREEN_ON);
			BroadcastReceiver mReceiver = new TxWthrReceiver();
			this.registerReceiver(mReceiver, it);
			it = new IntentFilter("tmi.li.txwthr.UPDATE");
			this.registerReceiver(mReceiver, it);
			
	        // Build the widget update && send a custom Broadcast so the widget is updated asap when the update is ready
			if(intent.hasExtra("Id")) {
				Bundle extras = intent.getExtras();
				int id = extras.getInt("Id");
				buildUpdate(this, id);
				this.sendBroadcast(new Intent("tmi.li.txwthr.UPDATE"));
			}
	    }

	    @Override
	    public IBinder onBind(Intent intent) {
	        return null;
	    }
	    

	    @SuppressWarnings("static-access")
		public void buildUpdate(Context context, int id) {
	        try {
	        	
	        	//updating the widget and appending the new infos to the old str
	        	//so we can save it again in the preferences
	        	TxPref txpref = new TxPref(TxPref.PREFS_NAME_TXWTHR);
	        	
	        	String preprefs = txpref.getPrefs(context, id);
		        String[] prefs = preprefs.split(";");
		        updt.getRss(prefs[2],prefs[3]);
		        
		      //FIXME : validate updt.desc/updt.current/updt.desc2
		        //alsdfjasdfaisejfasefsa 
		        String lang = txpref.getLang(context, id);
		        if(lang != null) {
		        	if(lang == "null") {
		        		Locale local = new Locale("en");
		        		local = local.getDefault();
		        		lang = checkLocal(local.toString());
		        		txpref.saveLang(context, id, lang);
		        	}
		        	Locale locale2 = new Locale(lang); 
		            Locale.setDefault(locale2);
		            Configuration config2 = new Configuration();
		            config2.locale = locale2;
		         // updating locale
		            this.getResources().updateConfiguration(config2, null);
		        }
		        
		        //FIXME :
		        String desc = getDesc(updt.wcode);
		        desc = desc.toUpperCase();
		        if(desc.contains(";")) {
		        	String[] str = desc.split(";");
		        	updt.desc = str[0];
		        	updt.desc2 = str[1];
		        }else {
		        	updt.desc = desc;
		        	updt.desc2= "";
		        }
		        String newprefs = prefs[0]+";"+prefs[1]+";"+prefs[2]+";"+prefs[3]+";"+updt.current+";"+updt.desc+";"+updt.desc2;
		        txpref.savePrefs(context, id, newprefs);  
		        
	        } catch (Exception e) {

	        }   
	       	        
	    }
	    
	    public String checkLocal(String str) {
	    	if(str.contains("en")) {
	    		return "en";
	    	}else if (str.contains("de")){
	    		return "de";
	    	}else if (str.contains("fr")) {
	    		return "fr";
	    	}else if(str.contains("ru")) {
	    		return "ru";
	    	}else {
	    		return "en";
	    	}
	    }
	    
	    public String getDesc(String wcode) {
	    	int _wcode = Integer.valueOf(wcode);
	    	wcode = Integer.toHexString(_wcode);
	    	String hex = "7f0600";
	    	if(_wcode < 16)
	    		return getString(Integer.parseInt(hex+"0"+wcode,16));
	    	return getString(Integer.parseInt(hex+wcode,16));
	    }
	    
	}

		
}